package com.xdxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.xdxc.JwtGenaner.JwtUtil;
import com.xdxc.dto.system.LoginDto;
import com.xdxc.model.dto.UserDto;
import com.xdxc.model.dto.UserRegisterDto;
import com.xdxc.model.entity.SysUser;
import com.xdxc.exception.CustomException;
import com.xdxc.feign.LoginRegisterFeign;
import com.xdxc.model.entity.User;
import com.xdxc.response.Result;
import com.xdxc.service.AuthService;
import com.xdxc.service.SysUserService;
import com.xdxc.utils.EncryptionUtils;
import com.xdxc.vo.LoginAdminVo;
import com.xdxc.vo.UserLoginVo;
import com.xdxc.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired

    private LoginRegisterFeign loginRegisterFeign;

    // 普通用户登录（通过邮箱）
    @Override
    public Result loginByEmail(LoginDto loginDto) {
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setEmail(loginDto.getEmail());
        userLoginVo.setPassword(loginDto.getPassword());
        Result<User> result = loginRegisterFeign.userLogin(userLoginVo);

        if (result.getCode()==1){
            User userData = result.getData();
            if (userData == null) {
                throw new CustomException(500, "用户数据解析失败");
            }
            UserDto user= UserDto.builder()
                    .id(userData.getId())
                    .userId(userData.getUserId())
                    .post(userData.getPost())
                    .avatar(userData.getAvatar())
                    .userName(userData.getUserName())
                    .build();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("user",user);
            hashMap.put("token", generateToken(userData.getEmail(),userData.getId(), userData.getRoles()));
            Result<HashMap<String, Object>> result1=Result.success(hashMap);
            return  result1;
        }else {
            throw new CustomException(401, result.getMsg());
        }
    }

    // 管理员登录（通过用户名）
    @Override
    public Result loginByUsername(LoginAdminVo loginAdminVo) {

        Result<SysUser> result= loginRegisterFeign.Login(loginAdminVo);

        if (result.getCode()==1){
            SysUser sysUserData = result.getData();
            if (sysUserData == null) {
                throw new CustomException(500, "用户数据解析失败");
            }
            SysUser sysUser1= SysUser.builder()
                    .id(sysUserData.getId())
                    .status(sysUserData.getStatus())
                    .roles(sysUserData.getRoles())
                    .phone(sysUserData.getPhone())
                    .userName(sysUserData.getUserName())
                    .avatar(sysUserData.getAvatar())
                    .description(sysUserData.getDescription())
                    .build();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("user",sysUser1);
            hashMap.put("token", generateToken(result.getData().getUserName(),result.getData().getId(), result.getData().getRoles()));
            Result result1=Result.success(hashMap);
            result1.setMsg("登录成功");
            return  result1;
        }else {
            throw new CustomException(401, result.getMsg());
        }
    }

    @Override
    public Result registerByEmail(UserRegisterDto userRegisterDto) {
        UserRegisterVo userRegisterVo = new UserRegisterVo();
        userRegisterVo.setConfirmPassword(userRegisterDto.getConfirmPassword());
        userRegisterVo.setPassword(userRegisterDto.getPassword());
        userRegisterVo.setEmail(userRegisterDto.getEmail());
        Boolean bo= loginRegisterFeign.userRegister(userRegisterVo);
        if (!bo){
            throw new CustomException(403,"用户注册失败，账号或已存在");
        }
        return Result.success("注册成功");
    }


    // 生成JWT Token
    private String generateToken(String identifier, Long userId,List<String> role) {
        String token = JwtUtil.generateToken(identifier,userId, role);

        // 将Token存入Redis，设置过期时间
        redisTemplate.opsForValue().set("token:" + token, identifier, 1, TimeUnit.HOURS);

        return token;
    }
    private String generateToken(String identifier) {

        // 将Token存入Redis，设置过期时间
        return null;
    }

}